package cn.sdstudio.service.impl;

import cn.hutool.json.JSONUtil;
import cn.sdstudio.model.PageResult;
import cn.sdstudio.model.Result;
import cn.sdstudio.entity.ScenicSpot;
import cn.sdstudio.dto.ScenicSpotDTO;
import cn.sdstudio.mapper.ScenicSpotMapper;
import cn.sdstudio.service.ScenicSpotService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

import static cn.sdstudio.constants.SystemConstants.PARAM_ERROR_CODE;
import static cn.sdstudio.constants.RedisConstant.SCENIC_SPOT;

@Service
@RequiredArgsConstructor
public class ScenicSpotServiceImpl extends BaseServiceImpl<ScenicSpotMapper, ScenicSpot> implements ScenicSpotService {
    @Autowired
    private  final ScenicSpotMapper scenicSpotMapper;
    @Autowired
    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public PageResult<ScenicSpotDTO> listScenicSpots(Integer page, Integer size, String keyword) {
        return null;
    }
    @Transactional(readOnly=true,timeout = 10)
    @Override
    public Result<ScenicSpot> queryScenicSpotById(Long id) {
        String key = SCENIC_SPOT + id;

        String scenic = stringRedisTemplate.opsForValue().get(key);
        if(StringUtils.isNotBlank(scenic)){
            //处理空值，防止缓存穿透
            if("NULL".equals(scenic)){
              return Result.error(PARAM_ERROR_CODE,   "景点不存在");
            }

            ScenicSpot bean = JSONUtil.toBean(scenic, ScenicSpot.class);
            return Result.success(bean);
        }

        ScenicSpot scenicSpot = scenicSpotMapper.selectById(id);
        if(scenicSpot ==null){
            //缓存空值
            stringRedisTemplate.opsForValue().set(key,"NULL",5, TimeUnit.MINUTES);
            return Result.error(PARAM_ERROR_CODE,"景点不存在");
        }
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(scenicSpot),1,TimeUnit.HOURS);

        return Result.success(scenicSpot);
    }

    @Override
    public void updateScenicSpot(ScenicSpot scenicSpot) {
        if(scenicSpot ==null || scenicSpot.getId()==null){
            throw new IllegalArgumentException("景点ID不能为空");
        }
        //获取分布式锁（防止并发更新）



    }


}
